package edu.whu.assignment8.impl;

import edu.whu.assignment8.dao.SupplierRepository;
import edu.whu.assignment8.entity.Supplier;
import edu.whu.assignment8.exception.GoodsAdminException;
import edu.whu.assignment8.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;


@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    SupplierRepository supplierRepository;

    @Override
    public Supplier addSupplier(Supplier supplier) throws GoodsAdminException {
        if (supplier.getId() != null) {
            if (supplierRepository.findById(supplier.getId()).isPresent()) {
                throw new GoodsAdminException("添加失败");
            }
        }
        return supplierRepository.saveAndFlush(supplier);
    }

    @Override
    public Supplier updateSupplier(long id, Supplier supplier) throws GoodsAdminException {
        if (!supplierRepository.findById(id).isPresent()) {
            throw new GoodsAdminException("修改失败");
        }
        return supplierRepository.saveAndFlush(supplier);
    }

    @Override
    public Page<Supplier> findSuppliers(String name, Pageable pageable){
        return supplierRepository.findByNameContaining(name,pageable);
    }

    @Override
    public Supplier getSupplier(long id){
        return supplierRepository.findById(id).get();
    }

    @Override
    public void deleteSupplier(long id) {
        supplierRepository.deleteById(id);
    }
}
